package com.xc.common.filter;

import com.xc.common.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  springmvc全局异常
 *  出现不能捕获异常的情况处理
 * Created by xiongcan on 2018/1/25.
 */
@Slf4j
//@Component
public class ExceptionResolver implements HandlerExceptionResolver {

    //  这里返回的是 ModelAndView 对象，如果是需要返回json，则转换为 MappingJacksonJsonView 对象
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                         Object o, Exception e) {
        log.error("==============================ExceptionResolver=================================");
        log.error("{} Exception by xiongcan",httpServletRequest.getRequestURI() , e);


        //  如果使用的jackson 2.x 那么使用 MappingJackson2JsonView
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        modelAndView.addObject("status", ResponseCode.ERROR.getCode());
        modelAndView.addObject("msg","自定义接口异常，详情请查看日志");
        modelAndView.addObject("data",e.toString());

//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.setViewName("protol/page/tishi/msg");
        return modelAndView;
    }

}
